package com.jiaolong.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取一个唯一的订单号
 */
public class CreMchOrderNoUtil {

    public static Long getOnlyNo() {
        Long onlyNo;
        try {
            SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator();
            onlyNo = snowflakeIdGenerator.nextId();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        return onlyNo;
    }

}

/**
 * 雪花算法
 */
class SnowflakeIdGenerator {

    private final long twepoch = 1288834974657L; // 开始时间戳，2010-11-04 09:42:54
    private final long workerIdBits = 5L;
    private final long datacenterIdBits = 5L;
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    private final long sequenceBits = 12L;

    private final long workerIdShift = sequenceBits;
    private final long datacenterIdShift = sequenceBits + workerIdBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long workerId;
    private long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator() throws UnknownHostException {

        // 检查workId的合法值
        if (workerId < 0 || workerId > maxWorkerId) {
            throw new IllegalArgumentException(String.format("workId值必须大于0并且小于%d", maxWorkerId));
        }

        // 检查datacenterId的合法值
        if (datacenterId < 0 || datacenterId > maxDatacenterId) {
            throw new IllegalArgumentException(
                    String.format("datacenterId值必须大于0并且小于%d", maxDatacenterId));
        }

        this.workerId = getWorkerId();
        this.datacenterId = getDatacenterId();
    }

    private long getWorkerId() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        return (long) ((ipAddr[ipAddr.length - 2] & 0B11) << 8) | (ipAddr[ipAddr.length - 1] & 0xFF);
    }

    private long getDatacenterId() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        return (long) ((ipAddr[ipAddr.length - 3] & 0xFF) << 3) | ((ipAddr[ipAddr.length - 2] & 0xFF) >> 5);
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }


}
